<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta HTTP-EQUIV="pragma" CONTENT="no-cache">
    <meta HTTP-EQUIV="Cache-Control" CONTENT="no-store, must-revalidate">
    <meta HTTP-EQUIV="expires" CONTENT="Wed, 26 Feb 1997 08:21:57 GMT">
    <meta HTTP-EQUIV="expires" CONTENT="0">

    <title>WebSocket QuickStart</title>
    <script src="../js/jquery-3.2.1.js"></script>
    <script src="../js/jquery-dateFormat.min.js"></script>
    <script type="text/javascript">
        var url = window.location.href;
        var splitedUrlArr = url.split("#");
        var visitUsername = '访客';
        if (splitedUrlArr.length > 1) {
            visitUsername = window.decodeURI(splitedUrlArr[1]);
        }
        var handshakeMsg = 'handshake';
        var webSocket = new WebSocket("ws://192.168.1.154:8086/websocket/message");
        webSocket.onopen = function (event) {
            console.log('WebSocket onopen event : ' , event);
            console.log('onopen WebSocket readyState : ' , webSocket.readyState);

            var data = {
                msg : handshakeMsg
            };
            webSocket.send(JSON.stringify(data));
        };

        webSocket.onmessage = function (event) {
            console.log('Receive Msg : ' , event.data);
            console.log('onmessage WebSocket readyState : ' , webSocket.readyState);
            var resObj = JSON.parse(event.data);
            if (resObj.username != visitUsername && resObj.msg != handshakeMsg) {
                $('#otherMsg').append('<br>' + resObj.sendTime + '<br>' + resObj.username + '<br>' + resObj.msg);
            }
        };

        webSocket.onclose = function (event) {
            console.log('WebSocket Connection Closed : ' , event);
            console.log('onclose WebSocket readyState : ' , webSocket.readyState);
        };

        webSocket.onerror = function (event) {
            console.log('WebSocket Error : ' , event);
            console.log('onerror WebSocket readyState : ' , webSocket.readyState);
        };
        
        function send() {
            var msg = document.getElementById('message').value;
            var sendMsg = {
                username : visitUsername ,
                msg : msg ,
                sendTime : $.format.date(new Date(),"yyyy-MM-dd HH:mm:ss")

            };
            $('#ownerMsg').append('<br>' + sendMsg.sendTime + '<br>' + sendMsg.username + '<br>' + sendMsg.msg);
            webSocket.send(JSON.stringify(sendMsg));
        }
        
    </script>
</head>
<body>

<div id="otherMsg" style="float: left; text-align: left; background-color: pink; width: 300px;height: 100%;"></div>
<div id="ownerMsg" style="float: left; text-align: right; background-color: pink; width: 300px;height: 100%;"></div>
<input id="message" style="width: 200px;height: 180px;" />
<button onclick="send();">发送消息</button>
</body>
</html>